package cn.lblbc.appstore.utils

import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.core.content.FileProvider
import cn.lblbc.appstore.BuildConfig
import cn.lblbc.appstore.module.download.StatusManager
import cn.lblbc.lib.LblApplication
import java.io.File


object AppUtils {
    private val tag = "AppUtils"
    fun install(context: Context, packageName: String, apkFilePath: String) {
        val intent = Intent(Intent.ACTION_VIEW)
        val file = File(apkFilePath)
        val uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".FileProvider", file)
        val type = "application/vnd.android.package-archive"
        intent.setDataAndType(uri, type)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        context.startActivity(intent)
        StatusManager.notifyInstallChanges(packageName, true)
    }

    fun generateDownloadApkName(): String {
        return Utils.getUUID() + ".apk"
    }

    fun isAppInstalled(packageName: String): Boolean {
        val packageManager = LblApplication.context.packageManager
        return try {
            packageManager.getApplicationInfo(packageName, 0)
            true
        } catch (e: PackageManager.NameNotFoundException) {
            false
        }
    }

    fun getVersionCode(packageName: String): Long {
        var versionCode = -1L

        getPackageInfo(LblApplication.context, packageName)?.let {
            versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                it.longVersionCode
            } else {
                it.versionCode.toLong()
            }
        }
        return versionCode
    }

    private fun getPackageInfo(context: Context, packageName: String): PackageInfo? {
        var apkInfo: PackageInfo? = null
        try {
            val manager = context.packageManager
            apkInfo = if (Build.VERSION.SDK_INT >= 33) {
                manager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(128L))
            } else {
                manager.getPackageInfo(packageName, 128)
            }
        } catch (e: Exception) {
        }
        return apkInfo
    }

    fun openApp(packageName: String) {
        val context = LblApplication.context
        try {
            val intent = context.packageManager.getLaunchIntentForPackage(packageName)
            context.startActivity(intent)
        } catch (e: Exception) {
            Log.e(tag, e.message ?: "")
        }
    }
}